package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Order;
import com.web.exiaodao.business.entity.Returnshoprecord;
import com.web.exiaodao.business.repository.OrderRepository;
import com.web.exiaodao.business.repository.ReturnshoprecordRepository;
import com.web.exiaodao.remote.service.ApiReturnshoprecordService;
import com.web.exiaodao.remote.vo.ReturnshoprecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2017-01-22 13:32:17
 * 类的说明：前端APIReturnshoprecord接口实现类
 **/
@Service("ApiReturnshoprecordService")
@Transactional(readOnly = false)
public class ApiReturnshoprecordServiceImpl extends BaseService<Returnshoprecord> implements ApiReturnshoprecordService{

	private static final Logger LOGGER = Logger.getLogger(ApiReturnshoprecordServiceImpl.class);

	@Autowired
	ReturnshoprecordRepository returnshoprecordRepository;

	@Autowired
	OrderRepository orderRepository;

	@Override
	public XaResult<ReturnshoprecordVo> findOne(Long tId) throws BusinessException {
		Returnshoprecord obj = returnshoprecordRepository.findByIdAndStatusNot(tId,XaConstant.Status.delete);
		XaResult<ReturnshoprecordVo> xr = new XaResult<ReturnshoprecordVo>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj),ReturnshoprecordVo.class));
			xr.getObject().setId(obj.getId());
			LOGGER.info("查询单个实体----->Returnshoprecord");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
			throw new BusinessException(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<List<ReturnshoprecordVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<Returnshoprecord> page = returnshoprecordRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Returnshoprecord.class), pageable);
		XaResult<List<ReturnshoprecordVo>> xr = new XaResult<List<ReturnshoprecordVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), ReturnshoprecordVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<List<ReturnshoprecordVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<Returnshoprecord> page = returnshoprecordRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Returnshoprecord.class), pageable);
		XaResult<List<ReturnshoprecordVo>> xr = new XaResult<List<ReturnshoprecordVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), ReturnshoprecordVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<ReturnshoprecordVo> multiOperate(String modelIds,
			Integer status) throws BusinessException {
		XaResult<ReturnshoprecordVo> xr = new XaResult<ReturnshoprecordVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				Returnshoprecord obj = returnshoprecordRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = returnshoprecordRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), ReturnshoprecordVo.class));
					xr.getObject().setId(obj.getId());
				}
			}
		}
		LOGGER.info("更改数据状态----->Returnshoprecord");
		return xr;
	}


    /**
     * 申请退款的接口
     * @param model
     * @return
     * @throws BusinessException
     */
	@Override
	public XaResult<ReturnshoprecordVo> createModel(Returnshoprecord model)
			throws BusinessException {
		XaResult<ReturnshoprecordVo> xr = new XaResult<ReturnshoprecordVo>();

		String orderNo = model.getOrderNo();
		Order order = orderRepository.findByOrderNoAndStatusNot(orderNo, XaConstant.Status.delete);
		if (XaUtil.isEmpty(order)) {
			xr.error("订单不存在("+ orderNo +")!");
			return xr;
		}
		if (Integer.parseInt(order.getOrderType()) == JConstant.Order_CommentType.GOODS ||
                Integer.parseInt(order.getOrderType()) == JConstant.Order_CommentType.GOODS_EXCHANGE ||
                Integer.parseInt(order.getOrderType()) == JConstant.Order_CommentType.ARTWORK) {
            //普通订单
            if ( !(NumberUtils.toInt(order.getOrderState()) == JConstant.OrderStatus.PAYED ||
                    NumberUtils.toInt(order.getOrderState()) == JConstant.OrderStatus.UN_CONSIGNEE ||
                    NumberUtils.toInt(order.getOrderState()) == JConstant.OrderStatus.UN_COMMENT ||
                    NumberUtils.toInt(order.getOrderState()) == JConstant.OrderStatus.SUCCES_TRADE ) ) {
                xr.error("商品订单只有支付成功的订单才能退款（"+ order.getOrderNo() + "-" + order.getOrderState() +"）");
                return xr;
            }
            if (model.getType() == 0) {//（0：仅退款  1:退货）
                if (NumberUtils.toInt(order.getOrderState()) != JConstant.OrderStatus.PAYED) {
                    xr.error("已经发货的商品只能退货");
                    return xr;
                }
            }
        } else {
		    //服务订单
            if ( NumberUtils.toInt(order.getOrderState()) != JConstant.OrderStatus.PAYED ) {
                xr.error("服务订单只有待消费状态才能退款（（"+ order.getOrderNo() + "-" + order.getOrderState() +"）");
                return xr;
            }
        }
        Returnshoprecord temp = returnshoprecordRepository.findByOrderNoAndStatusNot(orderNo, XaConstant.Status.delete);
        if (temp == null) {
        } else {
            temp.setOrderNo(XaUtil.isNotEmpty(model.getOrderNo()) ? model.getOrderNo() : temp.getOrderNo());
            temp.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : temp.getType());
            temp.setReason(XaUtil.isNotEmpty(model.getReason()) ? model.getReason() : temp.getReason());
            temp.setImgs(XaUtil.isNotEmpty(model.getImgs()) ? model.getImgs() : temp.getImgs());
            temp.setAuditAdvice(XaUtil.isNotEmpty(model.getAuditAdvice()) ? model.getAuditAdvice() : temp.getAuditAdvice());
            temp.setAuditTime(XaUtil.isNotEmpty(model.getAuditTime()) ? model.getAuditTime() : temp.getAuditTime());
            temp.setAuditor(XaUtil.isNotEmpty(model.getAuditor()) ? model.getAuditor() : temp.getAuditor());
        }
        temp = returnshoprecordRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(temp), ReturnshoprecordVo.class));
        xr.getObject().setId(temp.getId());

		order.setRefundStatus(JConstant.OrderRefundStatus.REFUNDING);
        order = orderRepository.save(order);

		LOGGER.info("新增数据成功 (退款申请成功)----->Returnshoprecord");
		return xr;
	}

	@Override
	public XaResult<ReturnshoprecordVo> updateModel(Returnshoprecord model)
			throws BusinessException {
		Returnshoprecord obj = returnshoprecordRepository.findOne(model.getId());
		XaResult<ReturnshoprecordVo> xr = new XaResult<ReturnshoprecordVo>();
		if (XaUtil.isNotEmpty(obj)) {
					obj.setOrderNo(XaUtil.isNotEmpty(model.getOrderNo()) ? model.getOrderNo() : obj.getOrderNo());
					obj.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : obj.getType());
					obj.setReason(XaUtil.isNotEmpty(model.getReason()) ? model.getReason() : obj.getReason());
					obj.setImgs(XaUtil.isNotEmpty(model.getImgs()) ? model.getImgs() : obj.getImgs());
					obj.setAuditAdvice(XaUtil.isNotEmpty(model.getAuditAdvice()) ? model.getAuditAdvice() : obj.getAuditAdvice());
					obj.setAuditTime(XaUtil.isNotEmpty(model.getAuditTime()) ? model.getAuditTime() : obj.getAuditTime());
					obj.setAuditor(XaUtil.isNotEmpty(model.getAuditor()) ? model.getAuditor() : obj.getAuditor());
				obj = returnshoprecordRepository.save(obj);
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj), ReturnshoprecordVo.class));
			xr.getObject().setId(obj.getId());
		} else {
			xr.error(XaConstant.Message.object_not_find);
		}
		LOGGER.info("编辑数据成功----->Returnshoprecord");
		return xr;
	}

}
